#include "pmu_gpio.h"
#include "driver_pmu.h"
#include "driver_system.h"

#define PORT_GPIO   GPIO_PORT_D
#define PORT_PIN    GPIO_BIT_5
#define PORT_FUNC   PORTD5_FUNC_D5
#define PORT_READ   pmu_portd_read
#define PORT_WRITE  pmu_portd_write

#define PORT_PIN1    GPIO_BIT_4
#define PORT_FUNC1   PORTD4_FUNC_D4
/*    pmu_gpio_init
*     PMU输出高低电平
*/
void pmu_gpio_init(void)
{
	pmu_set_pin_to_PMU(PORT_GPIO, (1<<PORT_PIN));
	//system_set_port_mux(PORT_GPIO, PORT_PIN, PORT_FUNC);
  pmu_set_pin_mux(PORT_GPIO,(1<<PORT_PIN),PMU_PIN_FUNC_GPIO);

	pmu_set_pin_dir(PORT_GPIO, (1<<PORT_PIN), GPIO_DIR_OUT);
	
	
	
		pmu_set_pin_to_PMU(PORT_GPIO, (1<<PORT_PIN1));
	//system_set_port_mux(PORT_GPIO, PORT_PIN, PORT_FUNC);
  pmu_set_pin_mux(PORT_GPIO,(1<<PORT_PIN1),PMU_PIN_FUNC_GPIO);

	pmu_set_pin_dir(PORT_GPIO, (1<<PORT_PIN1), GPIO_DIR_OUT);
	
	
	
	NVIC_EnableIRQ(PMU_IRQn);
	#if 1
	while(1)
	{
		PORT_WRITE(PORT_READ()|   (0x01<<PORT_PIN));
		co_delay_100us(10000);
		
		PORT_WRITE(PORT_READ()|   (0x01<<PORT_PIN1));
		co_delay_100us(10000);
		
		
    PORT_WRITE(PORT_READ() &~ (0x01<<PORT_PIN) );
		co_delay_100us(10000);	
		
		PORT_WRITE(PORT_READ() &~ (0x01<<PORT_PIN1) );
		co_delay_100us(10000);	
		
		
//			pmu_portd_write(pmu_portd_read()| 0xff/*(0x01<<5)*/);
//			printf("read pmu_portd_read=%x\r\n",pmu_portd_read());
//			 co_delay_100us(10000);
//			

//    pmu_portd_write(pmu_portd_read() &~(0xff) /*(0x01<<5)*/ );
//		printf("read pmu_portd_read=%x\r\n",pmu_portd_read());
//			co_delay_100us(10000);
		}
	#endif
	

}


/*    pmu_gpio_interrupt_init
*     PMU中断检测
*/
void pmu_gpio_interrupt_init(void)
{

  pmu_set_pin_to_PMU(PORT_GPIO, (1<<PORT_PIN));
  system_set_port_mux(PORT_GPIO, PORT_PIN, PORT_FUNC);
  pmu_set_pin_dir(PORT_GPIO, (1<<PORT_PIN), GPIO_DIR_IN);	
  pmu_port_wakeup_func_set(PORT_GPIO, (1<<PORT_PIN) );
  NVIC_EnableIRQ(PMU_IRQn);
	
}

void gpio_interrupt_callback(void)
{
	if(PORT_READ()&(1<<PORT_PIN))
	{
	   printf("release\r\n");
	}else
	{
	   printf("press\r\n");
	}

}
__attribute__((section("ram_code"))) void pmu_gpio_isr(uint32_t pin_value)
{
	gpio_interrupt_callback();
}



/*****************************************/
__attribute__((section("ram_code"))) void pmu_isr(void)  //PMU中断处理函数
{
    uint16_t state = pmu_get_isr_state();//获取pmu中断标志
	
		    if(state & PMU_GPIO_XOR_INT_STATUS)
				{
						uint32_t pin_value = ool_read32(PMU_REG_PORTA_LAST_STATUS);
						pmu_gpio_isr(pin_value);
						ool_write32(PMU_REG_PORTA_LAST_STATUS, pin_value);
				}
		
		pmu_clear_isr_state(state);  				//清除pmu中断标志
}
/*****************************************/